package me.leiusual.sharing.ui.home

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_home_search.*
import kotlinx.android.synthetic.main.fragment_home_search.view.*
import me.leiusual.sharing.R
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.home.adapter.HomeSearchAdapter
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-25
 * description:
 */
class HomeSearchFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_home_search, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }
    toolbar.setOnMenuItemClickListener {
      doSearch()
      true
    }

    view_pager.adapter = HomeSearchAdapter(childFragmentManager)
  }

  override fun onDestroy() {
    super.onDestroy()

    // 清除搜索关键词
    mainViewModel.searchKeyword(null)
  }

  /**
   * 执行搜索
   */
  private fun doSearch() {

    // 清除焦点
    val inputMethodManager = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(toolbar.edit_text_search.windowToken, 0)

    // 通知 sub fragment 搜索
    val text = toolbar.edit_text_search.text.toString()
    mainViewModel.searchKeyword(text)
  }
}